package com.zapi.notification.controller;

import com.zapi.notification.entity.Message;
import com.zapi.notification.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.util.Map;

/**
 * WebSocket消息处理器
 * 用于处理实时消息推送
 */
@Controller
public class WebSocketController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private MessageService messageService;

    /**
     * 处理用户加入聊天室
     */
    @MessageMapping("/join")
    @SendTo("/topic/public")
    public String joinChat(@Payload String username, SimpMessageHeaderAccessor headerAccessor) {
        // 添加用户到WebSocket会话
        headerAccessor.getSessionAttributes().put("username", username);
        return username + " 加入了聊天室";
    }

    /**
     * 处理公共消息
     */
    @MessageMapping("/chat")
    @SendTo("/topic/public")
    public String sendPublicMessage(@Payload String message) {
        return message;
    }

    /**
     * 处理私人消息
     */
    @MessageMapping("/private-message")
    public void sendPrivateMessage(@Payload Map<String, Object> payload) {
        String to = (String) payload.get("to");
        String message = (String) payload.get("message");
        
        // 发送私人消息
        messagingTemplate.convertAndSendToUser(to, "/queue/private", message);
    }

    /**
     * 推送系统通知
     */
    public void pushSystemNotification(Long userId, String message) {
        messagingTemplate.convertAndSendToUser(
            userId.toString(), 
            "/queue/notification", 
            message
        );
    }

    /**
     * 推送消息通知
     */
    public void pushMessageNotification(Long userId, Message message) {
        messagingTemplate.convertAndSendToUser(
            userId.toString(), 
            "/queue/message", 
            message
        );
    }

    /**
     * 广播系统消息
     */
    public void broadcastSystemMessage(String message) {
        messagingTemplate.convertAndSend("/topic/system", message);
    }

    /**
     * 发送消息到指定用户组
     */
    public void sendToUserGroup(String groupId, String message) {
        messagingTemplate.convertAndSend("/topic/group/" + groupId, message);
    }
} 